package Z11_6_optimistic;

import lombok.AllArgsConstructor;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author： pang-yun
 * @date： 2021-11-06 13:54
 * 功能目的 ：用于
 */

public class Atomic {
}

@AllArgsConstructor
class AccountCas implements Account {
    private AtomicInteger balance;

    @Override
    public Integer getBalance() {
        return balance.get();
    }

    @Override
    public void withdraw(Integer account) {
        while (true) {
            //1.获取余额的最新值
            int pre = balance.get();
            //2.要修改后的 余额值
            int next = pre - account;
            //3.最后真正的修改
            if (balance.compareAndSet(pre,next))
            {
                break;
            };
        }
    }
}

interface Account {
    public Integer getBalance();
    public void withdraw(Integer account);
}